package com.tdd.wx.users.mongo;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import com.tdd.wx.users.entity.WxUserPointRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * 微信用户管理
 *
 * @author loby
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class WxUserPointRecordHandler{

    private final WxUserPointRecordRepository wxUserPointRecordRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    public WxUserPointRecordHandler(WxUserPointRecordRepository wxUserPointRecordRepository) {
        this.wxUserPointRecordRepository = wxUserPointRecordRepository;
    }


    public Page<WxUserPointRecord> listPage(int current, int size, String unionid) {
        WxUserPointRecord r = new WxUserPointRecord();
        r.setUnionid(unionid);
        Example<WxUserPointRecord> example = Example.of(r);

        Pageable pageable = PageRequest.of((current - 1), size, Sort.Direction.DESC, "createTimer");
        Page<WxUserPointRecord> p = wxUserPointRecordRepository.findAll(example, pageable);
        return p;
    }

    public WxUserPointRecord save(WxUserPointRecord wxUserPointRecord) {
        return wxUserPointRecordRepository.save(wxUserPointRecord);
    }

    public void save(String unionid, String operation, String operationCode, BigDecimal point){
        WxUserPointRecord wxUserPointRecord = new WxUserPointRecord();
        wxUserPointRecord.setUnionid(unionid);
        wxUserPointRecord.setId(IdUtil.simpleUUID());
        wxUserPointRecord.setOperation(operation);
        wxUserPointRecord.setOperationCode(operationCode);
        wxUserPointRecord.setPoint(point);
        wxUserPointRecord.setCreateTimer(DateTime.now().getTime());
        wxUserPointRecord.setCreateTime(DateTime.now());
        this.save(wxUserPointRecord);
    }

}
